package cn.tedu.boot22.controller;

import cn.tedu.boot22.entity.User;
import cn.tedu.boot22.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
        //soutp
        System.out.println("user = " + user);
        try ( Connection conn= DBUtils.getConn();){
            String sql="insert into user value (null,?,?,?,?)";
            PreparedStatement ps=conn.prepareStatement(sql);
            //替换
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNick());
            ps.setInt(4,user.getAge());
            ps.executeUpdate();
            System.out.println("注册成功");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功";
    }
    @RequestMapping("/login")
    @ResponseBody
    public String login(User user){
        try (Connection conn=DBUtils.getConn();){
            String sql="select count(*) from user where username=? password=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            //执行查询
            ResultSet rs=ps.executeQuery();
            rs.next();//游标向下移动
            int count=rs.getInt(1);
            if(count>0){
                return "登陆成功";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户名或密码错误 <a href='/login.html'>重新登陆</a>";
    }
}
